


package ciicos.controller;

import ciicos.service.LineProjectService;
import ciicos.util.convert.DataDicConvert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ciicos.base.ActionResult;
import ciicos.base.vo.PageListVO;
import ciicos.base.vo.PaginationVO;
import ciicos.exception.DataException;
import org.springframework.transaction.annotation.Transactional;
import ciicos.model.lineplace.*;
import ciicos.model.lineplace.LinePlacePagination;
import ciicos.entity.*;
import ciicos.entity.LinePlaceImagesEntity;
import ciicos.util.*;
import ciicos.base.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ciicos.entity.LinePlaceEntity;
import ciicos.service.LinePlaceService;
import ciicos.service.LinePlaceImagesService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.Valid;
import java.io.IOException;

import ciicos.util.GeneraterSwapUtil;

import java.util.stream.Collectors;
import java.util.*;


/**
 * 位置管理
 *
 * @版本： V3.2.0
 * @版权：
 * @作者： 企业研发中心
 * @日期： 2025-10-03
 */
@Slf4j
@RestController
@Api(tags = "位置管理", value = "line")
@RequestMapping("/api/line/LinePlace")
public class LinePlaceController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private LinePlaceService linePlaceService;

    @Autowired
    private LinePlaceImagesService linePlaceImagesService;

    @Autowired
    private LineProjectService lineProjectService;

    @Autowired
    private DataDicUtil dataDicUtil;

    /**
     * 线缆统计-数量
     *
     * @param
     * @return
     */
    @ApiOperation("线缆统计-数量")
    @PostMapping("/count")
    public ActionResult count() throws IOException {
        long count = linePlaceService.count();
        return ActionResult.success(count);
    }

    /**
     * 线缆统计-类别
     *
     * @param
     * @return
     */
    @ApiOperation("线缆统计-类别")
    @PostMapping("/getTypeCount")
    public ActionResult getTypeCount() throws IOException {
        long count = linePlaceService.getTypeCount();
        return ActionResult.success(count);
    }
    /**
     * 列表
     *
     * @param linePlacePagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody LinePlacePagination linePlacePagination) throws IOException {
        PageListVO vo = new PageListVO();

        //1.获取主表数据
        List<LinePlaceEntity> list = linePlaceService.getList(linePlacePagination);
        if(list==null || list.size()==0){
            PaginationVO page = JsonUtil.getJsonToBean(linePlacePagination, PaginationVO.class);
            vo.setPagination(page);
            vo.setList(new ArrayList());
            return ActionResult.success(vo);
        }
        //2.获取字表数据
        //2.1获取所有的id
        List<String> parentIdList = list.stream().map(LinePlaceEntity::getId).collect(Collectors.toList());
        //2.2根据id查询字表
        List<LinePlaceImagesEntity> linePlaceImagesList = linePlaceService.getLinePlaceImagesMapList(parentIdList);

        //3.字表数据按照id分组,同时转换为输出格式
        Map<String,List<LinePlaceImagesModel>> LinePlaceImagesModelMapList = new HashMap<>();
        if(ListUtil.isNotEmpty(linePlaceImagesList)) {
            //3.1字表中涉及数据字典的数据都要替换下
            DataDicConvert direction = dataDicUtil.getDataDicConvert("743893439766069893");
            //3.2遍历子表,
            for (LinePlaceImagesEntity entity : linePlaceImagesList) {
                String placeid = entity.getPlaceid();
                //转换为输出格式
                LinePlaceImagesModel model = JsonUtil.getJsonToBean(entity, LinePlaceImagesModel.class);
                //使用数据字典更新
                model.setDirection(direction.getCodeWithName(model.getDirection()));
                //校验文件名
                model.setImage(generaterSwapUtil.getFileNameInJson(model.getImage()));
                LinePlaceImagesModelMapList.computeIfAbsent(placeid, k -> new ArrayList<>()).add(model);
            }
        }
        //3.转为输出格式
        List<LinePlaceListVO> listVO = JsonUtil.getJsonToList(list, LinePlaceListVO.class);
        for (LinePlaceListVO linePlaceVO : listVO) {
            linePlaceVO.setCode_name(linePlaceVO.getCode());
            linePlaceVO.setName_name(linePlaceVO.getName());
            linePlaceVO.setPlacex_name(linePlaceVO.getPlacex());
            linePlaceVO.setPlacey_name(linePlaceVO.getPlacey());
            linePlaceVO.setPlacez_name(linePlaceVO.getPlacez());
            linePlaceVO.setRemark_name(linePlaceVO.getRemark());
            linePlaceVO.setCreateTime_name(linePlaceVO.getCreateTime()==null?null:new Date(linePlaceVO.getCreateTime()));
            linePlaceVO.setUpdateTime_name(linePlaceVO.getUpdateTime()==null?null:new Date(linePlaceVO.getUpdateTime()));
            //插入子表数据
            linePlaceVO.setLinePlaceImagesList(LinePlaceImagesModelMapList.get(linePlaceVO.getId()));
        }
        //主表中涉及数据字典的,统一更新
        dataDicUtil.replaceCodeWithName(listVO,"743831076564107333", LinePlaceListVO::getType,LinePlaceListVO::setType_name);
        dataDicUtil.replaceCodeWithName(listVO,"753971265089306693", LinePlaceListVO::getWellType,LinePlaceListVO::setWellType_name);
        dataDicUtil.replaceCodeWithName(listVO,"743831165676290117", LinePlaceListVO::getStatus,LinePlaceListVO::setStatus_name);
        dataDicUtil.replaceCodeWithName(listVO,"743831254457122885", LinePlaceListVO::getStatuswork,LinePlaceListVO::setStatuswork_name);
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(linePlacePagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param linePlaceForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid LinePlaceForm linePlaceForm) throws DataException {
        ActionResult actionResult = linePlaceService.checkForm(linePlaceForm, "0");
        if (actionResult.getCode() != 200) {
            return actionResult;
        }
        String mainId = RandomUtil.uuId();

        LinePlaceEntity entity = JsonUtil.getJsonToBean(linePlaceForm, LinePlaceEntity.class);
        entity.setId(mainId);
        //赋默认值
        if(entity.getStatus()==null){
            entity.setStatus("1");
        }
        if(entity.getStatuswork()==null){
            entity.setStatuswork("0");
        }
        if(entity.getType()==null){
            //管井
            entity.setType("1");
        }
        if(StringUtil.equals(entity.getType(),"1")){
            entity.setWellType("99");
        }
        Date nowDate=new Date();
        entity.setCreateTime(nowDate);
        entity.setUpdateTime(nowDate);
        linePlaceService.save(entity);
        if (linePlaceForm.getLineplaceimagesList() != null) {
            List<LinePlaceImagesEntity> LinePlaceImagesList = JsonUtil.getJsonToList(linePlaceForm.getLineplaceimagesList(), LinePlaceImagesEntity.class);
            for (LinePlaceImagesEntity entitys : LinePlaceImagesList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setPlaceid(entity.getId());
                linePlaceImagesService.save(entitys);
            }
        }

        return ActionResult.success("创建成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<LinePlaceInfoVO> info(@PathVariable("id") String id) {
        LinePlaceEntity entity = linePlaceService.getInfo(id);
        LinePlaceInfoVO vo = JsonUtil.getJsonToBean(entity, LinePlaceInfoVO.class);

        List<LinePlaceImagesEntity> LinePlaceImagesList = linePlaceService.getLinePlaceImagesList(id);
        vo.setLinePlaceImagesList(JsonUtil.getJsonToList(LinePlaceImagesList, LinePlaceImagesModel.class));

        //获取工程作业
        vo.setProjectStatus(lineProjectService.getProjectStatusByLinePlace("1",vo.getId()));
        return ActionResult.success(vo);
    }

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<LinePlaceListVO> detailInfo(@PathVariable("id") String id) {
        LinePlaceEntity entity = linePlaceService.getById(id);
        LinePlaceListVO vo = JsonUtil.getJsonToBean(entity, LinePlaceListVO.class);

        //子表数据转换
        List<LinePlaceImagesEntity> linePlaceImagesList = linePlaceService.getLinePlaceImagesList(id);
        List<LinePlaceImagesModel> linePlaceImagesModelList = JsonUtil.getJsonToList(linePlaceImagesList, LinePlaceImagesModel.class);
        for (LinePlaceImagesModel linePlaceImagesModel : linePlaceImagesModelList) {
            linePlaceImagesModel.setDirection(generaterSwapUtil.getDicName(linePlaceImagesModel.getDirection(), "743893439766069893"));
            linePlaceImagesModel.setImage(generaterSwapUtil.getFileNameInJson(linePlaceImagesModel.getImage()));
        }
        vo.setLinePlaceImagesList(linePlaceImagesModelList);

        vo.setCreateTime_name(vo.getCreateTime()==null?null:new Date(vo.getCreateTime()));
        vo.setUpdateTime_name(vo.getUpdateTime()==null?null:new Date(vo.getUpdateTime()));

        vo.setCode_name(vo.getCode());
        vo.setName_name(vo.getName());
        vo.setPlacex_name(vo.getPlacex());
        vo.setPlacey_name(vo.getPlacey());
        vo.setPlacez_name(vo.getPlacez());
        vo.setType_name(generaterSwapUtil.getDicName(vo.getType(), "743831076564107333"));
        vo.setWellType_name(generaterSwapUtil.getDicName(vo.getWellType(), "753971265089306693"));
        vo.setStatus_name(generaterSwapUtil.getDicName(vo.getStatus(), "743831165676290117"));
        vo.setStatuswork_name(generaterSwapUtil.getDicName(vo.getStatuswork(), "743831254457122885"));
        vo.setRemark_name(vo.getRemark());
        String projectStatus=StringUtil.equals(lineProjectService.getProjectStatusByLinePlace("1",vo.getId()),"1")?"1":StringUtil.equals(vo.getStatuswork(),"1")?"2":"0";
        vo.setProjectStatus(projectStatus);
        switch (projectStatus){
            case "0": vo.setProjectStatus_name("正常"); break;
            case "1": vo.setProjectStatus_name("维护中"); break;
            case "2": vo.setProjectStatus_name("施工中"); break;
        }
        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @param linePlaceForm
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid LinePlaceForm linePlaceForm) throws DataException {
        ActionResult actionResult = linePlaceService.checkForm(linePlaceForm, id);
        if (actionResult.getCode() != 200) {
            return actionResult;
        }
        LinePlaceEntity entity = linePlaceService.getInfo(id);
        if (entity != null) {
            LinePlaceEntity subentity = JsonUtil.getJsonToBean(linePlaceForm, LinePlaceEntity.class);
            subentity.setCreateTime(entity.getCreateTime());
            subentity.setUpdateTime(new Date());
            boolean b1 = linePlaceService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            QueryWrapper<LinePlaceImagesEntity> LinePlaceImagesqueryWrapper = new QueryWrapper<>();
            LinePlaceImagesqueryWrapper.lambda().eq(LinePlaceImagesEntity::getPlaceid, entity.getId());
            linePlaceImagesService.remove(LinePlaceImagesqueryWrapper);
            if (linePlaceForm.getLineplaceimagesList() != null) {
                List<LinePlaceImagesEntity> LinePlaceImagesList = JsonUtil.getJsonToList(linePlaceForm.getLineplaceimagesList(), LinePlaceImagesEntity.class);
                for (LinePlaceImagesEntity entitys : LinePlaceImagesList) {


                    entitys.setId(RandomUtil.uuId());
                    entitys.setPlaceid(entity.getId());
                    linePlaceImagesService.save(entitys);
                }
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 大屏更新
     *
     * @param id
     * @param linePlaceForm
     * @return
     */
    @PutMapping("/dp/{id}")
    @Transactional
    @ApiOperation("大屏更新")
    public ActionResult updateDp(@PathVariable("id") String id, @RequestBody @Valid LinePlaceForm linePlaceForm) throws DataException {
        ActionResult actionResult = linePlaceService.checkForm(linePlaceForm, id);
        if (actionResult.getCode() != 200) {
            return actionResult;
        }
        LinePlaceEntity entity = linePlaceService.getInfo(id);
        if (entity != null) {
            entity.setName(linePlaceForm.getName());
            entity.setPlacex(linePlaceForm.getPlacex());
            entity.setPlacey(linePlaceForm.getPlacey());
            entity.setPlacez(linePlaceForm.getPlacez());
            entity.setUpdateTime(new Date());
            boolean b1 = linePlaceService.updateById(entity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        LinePlaceEntity entity = linePlaceService.getInfo(id);
        if (entity != null) {
            linePlaceService.delete(entity);
            QueryWrapper<LinePlaceImagesEntity> queryWrapperLinePlaceImages = new QueryWrapper<>();
            queryWrapperLinePlaceImages.lambda().eq(LinePlaceImagesEntity::getPlaceid, entity.getId());
            linePlaceImagesService.remove(queryWrapperLinePlaceImages);
        }
        return ActionResult.success("删除成功");
    }

    /**
     * 根据线缆查询管井列表
     *
     * @param id
     * @return
     */
    @ApiOperation("根据线缆查询管井列表")
    @GetMapping("/getLineListByPlaceId/{id}")
    @Transactional
    public ActionResult getLineListByPlaceId(@PathVariable("id") String id){
        List<LineLineEntity> linePlaceEntityList = linePlaceService.getLineListByPlaceId(id);
        return ActionResult.success(linePlaceEntityList);
    }


}
